var mainSwitch;
var keys;
var values = [];
var jsonObj;
$(document).ready(function(){
    reloadByAjax();
});

function reloadByAjax() {
    values = [];
    $.ajax({
        url:"/initConfig",
        data:{dateTime: Math.random()},
        success:function (data) {//初始化页面内容
            jsonObj = JSON.parse(data);
            mainSwitch = jsonObj.MAINSWITCH;
            if (mainSwitch === "1")
                $("#switch_1").prop("checked",true);
            else
                $("#switch_0").prop("checked",true);
            keys = Object.keys(jsonObj);
            var groupStr = "";
            var tradeStr = "";
            for (var i = 0; i < keys.length; i++){
                var key = keys[i];
                var value = jsonObj[key];
                values.push(value);
                if (key.indexOf("CONFIG|")===0)
                    groupStr = createStr(i,key,value,groupStr,"group");
                if (key.indexOf("TRADECONFIG|")===0)
                    tradeStr = createStr(i,key,value,tradeStr,"trade");
            }
            $("#groupBody-1").empty();
            if ($('.datatable-1').hasClass('dataTable')) {
                var dttable = $('.datatable-1').dataTable();
                dttable.fnClearTable(); //清空一下table
                dttable.fnDestroy(); //还原初始化了的datatable
            }
            if ($('.datatable-2').hasClass('dataTable')) {
                var dttable = $('.datatable-2').dataTable();
                dttable.fnClearTable(); //清空一下table
                dttable.fnDestroy(); //还原初始化了的datatable
            }
            $(".datatable-1").find("tbody").html(groupStr);
            $(".datatable-2").find("tbody").html(tradeStr);
            $('.datatable-1').dataTable();
            $('.datatable-2').dataTable();
            $('.dataTables_paginate').addClass("btn-group datatable-pagination");
            $('.dataTables_paginate > a').wrapInner('<span />');
            $('.dataTables_paginate > a:first-child').append('<i class="icon-chevron-left shaded"></i>');
            $('.dataTables_paginate > a:last-child').append('<i class="icon-chevron-right shaded"></i>');

            $("#sortGroup-1").click();
            $("#sortGroup-2").click();
        }
    })
}

function createStr(i,key,value,orginStr,flag) {
    if (i % 2 === 0){
        orginStr += '<tr class="even">';
    } else {
        orginStr += '<tr class="odd">';
    }
    if (flag === "group")
        orginStr += '<td><input type="radio" name="group" onclick="updateGroup(\''+key+'\',\''+value+'\')"></td>';
    if (flag === "trade")
        orginStr += '<td><input type="radio" name="trade" onclick="updateTrade(\''+key+'\',\''+value+'\')"></td>';
    orginStr += '<td>'+key+'</td>';
    orginStr += '<td>'+value+'</td>';
    orginStr += '<td><label style="color: blue" onclick="deleteKey(\''+key+'\')">删除</label></td></tr>';
    return orginStr;
}
function changeMainSwitch(id){
    var r;
    if (id === "0")
        r = confirm("请确认您即将关闭限流服务！");
    if (id === "1")
        r = confirm("请确认您即将开启限流服务！");
    if (r === true){
        //ajax操作redis
        $.ajax({
            url:"/updateSwitch",
            data:{switchValue:id,dateTime: Math.random()},
            success:function (data) {
                alert("操作成功！");
            }
        })
    } else {
        if (id !== mainSwitch)
            $("#switch_"+Math.abs(1-id)).prop("checked",true);
    }
}

function deleteKey(key) {
    if (values.indexOf(key.substr(7))>=0){
        alert("该限流组配置已在交易配置中生效，请先修改对应的限流交易配置！");
        return;
    }
    if (confirm("确认删除配置"+key+"?")){
        $.ajax({
            url:"/deleteKey",
            async:false,
            data:{key:key,dateTime: Math.random()},
            success:function (data) {
                alert("操作成功！");
                reloadByAjax();
            }
        })
    }
}
// function removeRow(obj) {
//     if ($(obj.parentNode).parent().parent().attr("id")==="groupBody-1"){
//         var oTable = $('.datatable-1').dataTable();
//     }
//     if ($(obj.parentNode).parent().parent().attr("id")==="groupBody-2"){
//         var oTable = $('.datatable-2').dataTable();
//     }
//     var aPos = oTable.fnGetPosition( obj.parentNode );
//     oTable.fnDeleteRow(aPos[0],null,true);
// }
function updateGroup(key,value) {
    $("#group_id").val(key.substr(7));
    var arr = value.split("|");
    $("#group_sum").val(arr[1]);
    $("#group_timeOut").val(arr[3]);
}
function saveGroup() {
    var group = $("#group_id").val();
    var key = "CONFIG|"+group;
    var value = "B|"+$("#group_sum").val()+"|T|"+$("#group_timeOut").val();
    var re = /(^[1-9]\d*$)/ ;
    var keyArr= [] ,valueArr = [];
    if (group==null||group===""||group.indexOf(" ")>=0){
        alert("限流组为空或包含空格！");
        return;
    }
    if (!re.test($("#group_sum").val())||!re.test($("#group_timeOut").val())){
        alert("限流参数需为整数！");
        return;
    }
    if (keys.indexOf(key) >= 0){
        if(confirm("限流组"+$("#group_id").val()+"已经存在，即将执行更新操作！")){
            keyArr.push(key);
            valueArr.push(value);
            save(keyArr,valueArr);
        }
    }else{
        keyArr.push(key);
        valueArr.push(value);
        save(keyArr,valueArr);
    }
}
function save(keyArr,valueArr) {
    // valueArr = encodeURIComponent(valueArr);
    $.ajax({
        url:"/updateKeys",
        type:"post",
        data:{keys:keyArr,values:valueArr,dateTime: Math.random()},
        traditional:true,
        success:function () {
            alert("操作成功！");
            reloadByAjax();
        }
    })
}
function saveTrade(){
    var channel = $("#channelSelect").val();
    var trade = $("#tradeSelect").val();
    var tradeGroup = $("#tradeGroup").val();
    var successStr = $("#successStr").val();
    var failureStr = $("#failureStr").val();
    var key = "TRADECONFIG|"+trade+"|"+channel;
    var keyArr = [],valueArr = [];
    if (channel === "0"){
        alert("请选择渠道！");
        return;
    }
    if (trade === "0"){
        alert("请选择交易！");
        return;
    }
    if (tradeGroup==null||tradeGroup===""||tradeGroup.indexOf(" ")>=0){
        alert("限流组为空或包含空格！");
        return;
    }
    if (keys.indexOf(key)>=0){
        if (confirm("限流交易"+key+"已经存在，即将执行更新操作！")){
            keyArr.push(key);
            valueArr.push(tradeGroup);
            var key1 = channel+"|"+trade+"|SUCCESS";
            keyArr.push(key1);
            valueArr.push(successStr);
            var key2 = channel+"|"+trade+"|FAILURE";
            keyArr.push(key2);
            valueArr.push(failureStr);
            save(keyArr,valueArr);
            if (keys.indexOf("CONFIG|"+tradeGroup)<0){
                alert("请注意！当前配置的限流组不存在！");
            }
        }
    } else {
        keyArr.push(key);
        valueArr.push(tradeGroup);
        var key1 = channel+"|"+trade+"|SUCCESS";
        keyArr.push(key1);
        valueArr.push(successStr);
        var key2 = channel+"|"+trade+"|FAILURE";
        keyArr.push(key2);
        valueArr.push(failureStr);
        save(keyArr,valueArr);
        if (keys.indexOf("CONFIG|"+tradeGroup)<0){
            alert("请注意！当前配置的限流组不存在！");
        }
    }

}
function updateTrade(key,value){
    var arr = key.split("|");
    $("#tradeGroup").val(value);
    $("#channelSelect").val(arr[2]);
    $("#tradeSelect").val(arr[1]);
    var successKey = arr[2]+"|"+arr[1]+"|SUCCESS";
    var failuerKey = arr[2]+"|"+arr[1]+"|FAILURE";
    $("#successStr").val(jsonObj[successKey]);
    $("#failureStr").val(jsonObj[failuerKey]);
}
if (!Object.keys) {
    Object.keys = (function () {
        var hasOwnProperty = Object.prototype.hasOwnProperty,
            hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
            dontEnums = [
                'toString',
                'toLocaleString',
                'valueOf',
                'hasOwnProperty',
                'isPrototypeOf',
                'propertyIsEnumerable',
                'constructor'
            ],
            dontEnumsLength = dontEnums.length;

        return function (obj) {
            if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');

            var result = [];

            for (var prop in obj) {
                if (hasOwnProperty.call(obj, prop)) result.push(prop);
            }

            if (hasDontEnumBug) {
                for (var i = 0; i < dontEnumsLength; i++) {
                    if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
                }
            }
            return result;
        }
    })()
}

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (elt /*, from*/) {
        var len = this.length >>> 0;
        var from = Number(arguments[1]) || 0;
        from = (from < 0)
            ? Math.ceil(from)
            : Math.floor(from);
        if (from < 0)
            from += len;
        for (; from < len; from++) {
            if (from in this &&
                this[from] === elt)
                return from;
        }
        return -1;
    };
}